<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box img {
            width: 100px
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        // 定义红绿灯类
        function TrafficLight() {
            // 颜色属性，一开始都是红色
            // 红包1， 绿色3， 黄色2
            this.color = 1;
            // this表示实例
            this.init();
            this.bindEvent();
        }
        TrafficLight.prototype.init = function() {
            // 创建自己的dom
            this.dom = document.createElement('img');
            this.dom.src = '../images/' + this.color + '.jpg'
            box.appendChild(this.dom)
        }
        TrafficLight.prototype.bindEvent = function() {
            // 备份上下文,这里的this是js实例
            var self = this;
            // 当自己的dom被点击时
            this.dom.onclick = function() {
                // this为dom, self为实例
                console.log(this, self);
                // 当被点击的时候，调用自己的changeColor方法
                self.changeColor()
            }
        }
        TrafficLight.prototype.changeColor = function() {
            // 改变自己的color属性
            this.color++
                if (this.color == 4) {
                    this.color = 1
                }
            this.dom.src = '../images/' + this.color + '.jpg'
        }
        var box = document.getElementById('box')
        var count = 1;
        while (count--) {
            new TrafficLight();
        }
    </script>
</body>

</html>